//
//  MapViewController.swift
//  GZMarathon
//
//  Created by apple on 2021/10/31.
//

import UIKit
import MapKit
import CoreLocation
import SVProgressHUD



class PinAnnotation : NSObject,MKAnnotation {
    private var coord: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: 0,longitude: 0)

    var coordinate: CLLocationCoordinate2D {
        get {
            return coord
        }
    }
    var title: String?
    var subtitle: String?
    
    var tag: Int?

    func setCoordinate(newCoordinate: CLLocationCoordinate2D) {
        self.coord = newCoordinate
    }
}


class MapViewController: UIViewController, CLLocationManagerDelegate{

    @IBOutlet weak var icon: UIImageView!
    @IBOutlet weak var aedAdress: UILabel!
    @IBOutlet weak var connect: UILabel!
    @IBOutlet weak var person: UILabel!
    @IBOutlet weak var aedId: UILabel!
    @IBOutlet weak var aedname: UILabel!
    @IBOutlet weak var currentAdress: UILabel!
    @IBOutlet weak var detailView: UIView!
    @IBOutlet weak var mapView: MKMapView!
    
    var currentAdressStr = ""
    
    var locationManager: CLLocationManager!
    
    var list: GZAEDList?
    
    var mapType = 0 //0.单个 1.多个
    var AEDList:[GZAEDList]?
    
    
    
    
    private lazy var alertSheet : UIAlertController = {
        let alertSheet = UIAlertController(title: "导航", message: "", preferredStyle: UIAlertController.Style.actionSheet)
            return alertSheet
        }()
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        mapView.mapType = MKMapType.standard
        mapView.userTrackingMode    = MKUserTrackingMode.followWithHeading
        mapView.showsUserLocation   = true
        mapView.delegate            = self
        if (CLLocationManager.locationServicesEnabled()){
            locationManager = CLLocationManager()
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.distanceFilter  = 10.0
            locationManager.delegate        = self
            locationManager.requestWhenInUseAuthorization()
            locationManager.startUpdatingLocation()
        }

        
        
        setData()

        
        
        setAlertSheet()
        
        let tap = UITapGestureRecognizer()
        tap.addTarget(self, action: #selector(tapClick))
        
        icon.addGestureRecognizer(tap)
        // Do any additional setup after loading the view.
    }
    @objc func tapClick(){
        
        self.present(alertSheet, animated: true, completion: nil)
        
    }
    
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.navigationBar.isHidden = true
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
      
        navigationController?.navigationBar.isHidden = false
    }
    
    func setData(){
        
        
        
        if(mapType == 0){
            aedname.text = list?.aed_name
            aedId.text = "\(list?.id ?? 0)"
            person.text = list?.aed_contacts
            connect.text = list?.aed_contactnum
            aedAdress.text = list!.province_name + list!.city_name + list!.region_name + list!.aed_address
        }else{
            detailView.isHidden = true
        }
        
    }
    
    
    func setmore(p:Int){
        detailView.isHidden = false
        aedname.text = AEDList?[p].aed_name
        aedId.text = "\(AEDList?[p].id ?? 0)"
        person.text = AEDList?[p].aed_contacts
        connect.text = AEDList?[p].aed_contactnum
        aedAdress.text = (AEDList?[p].province_name)! + (AEDList?[p].city_name)! + (AEDList?[p].region_name)! + (AEDList?[p].aed_address)!
    }
    
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let location = locations.last{
            let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
            let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
            
            
            
            let geoCoder:CLGeocoder = CLGeocoder.init()
                    geoCoder.reverseGeocodeLocation(location, completionHandler: {(placemarks,error) in
                        
                        // 如果断网或者定位失败
                        if placemarks == nil{
                            return
                        }
             
                        let placeMark:CLPlacemark = placemarks![0]
                        
                        //详细地址
                        self.currentAdress.text = "\(placeMark.administrativeArea ?? "")\(placeMark.locality ?? "")\(placeMark.subLocality ?? "")\(placeMark.thoroughfare ?? "")"
                        self.currentAdressStr = self.currentAdress.text ?? ""
                    });
  
            if(self.currentAdressStr == ""){
             
                if(mapType == 0){
                    let annotation = MKPointAnnotation()
                    annotation.coordinate = CLLocationCoordinate2D(latitude: Double(list!.aed_latitude)!, longitude:  Double(list!.aed_longitude)!)
                    
                    self.mapView.addAnnotation(annotation)
                    self.mapView.setRegion(region, animated: true)
                }else{
                    
                    if let AEDList = AEDList{
                        for i in 0...(AEDList.count - 1){
                            
                            
                            let pinAnnotation = PinAnnotation()
                            
                            pinAnnotation.setCoordinate(newCoordinate: CLLocationCoordinate2D(latitude: Double(AEDList[i].aed_latitude)!, longitude:  Double(AEDList[i].aed_longitude)!))
                            pinAnnotation.tag = i
                            pinAnnotation.title = AEDList[i].aed_name
                            
//                            pinAnnotation.subtitle = AEDList[i].aed_contacts
                            mapView.addAnnotation(pinAnnotation)

                            

                        }

                    }
                    
                                        
                }
                
                
            }
            
        }
    }
    
 
    @objc func selectQH(){
        print("11")
    }
    

    private func setAlertSheet () {
        let sheetOptionO  = UIAlertAction(title: "高德地图", style: UIAlertAction.Style.default) { (action) in
            
            
            if UIApplication.shared.canOpenURL(URL.init(string: "iosamap://")!) {
                let urlString     = "iosamap://navi?sourceApplication=随便写&backScheme=随便写&lat=\(self.list!.aed_latitude)&lon=\(self.list!.aed_longitude)&dev=0&style=2"
                let escapedString = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
                UIApplication.shared.openURL(URL.init(string: escapedString!)!)
            }else{
                SVProgressHUD.showError(withStatus: "您没有安装高德地图")
            }
            
            self.alertSheet.dismiss(animated: true, completion: nil)
            
        }
        
        let sheetOptionT       = UIAlertAction(title: "百度地图", style: UIAlertAction.Style.default) { (action) in
            
            if UIApplication.shared.canOpenURL(URL.init(string: "baidumap://")!) {
            //注意：origin={{我的位置}}不要变；目的地随便写
            let urlString     = "baidumap://map/direction?origin={{我的位置}}&destination=latlng:\(self.list!.aed_latitude),\(self.list!.aed_longitude)|name=\(self.currentAdressStr)&mode=driving&coord_type=gcj02"
            let escapedString = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
            UIApplication.shared.openURL(URL.init(string: escapedString!)!)
                
            }else{
                SVProgressHUD.showError(withStatus: "您没有安装百度地图")
              
            }
            
            self.alertSheet.dismiss(animated: true, completion: nil)
            
        }
        let sheetOptionHidden  = UIAlertAction(title: "取消", style: UIAlertAction.Style.default) { (action) in
            
            self.alertSheet.dismiss(animated: true, completion: nil)
            
        }
 
        alertSheet.addAction(sheetOptionO)
        alertSheet.addAction(sheetOptionT)
        alertSheet.addAction(sheetOptionHidden)

    }
}

extension MapViewController : MKMapViewDelegate {

    
    func mapView(_ mapView: MKMapView,annotationView view: MKAnnotationView,calloutAccessoryControlTapped control: UIControl) {
        if let annotation = view.annotation{
            let v = annotation as! PinAnnotation
            
            setmore(p: v.tag ?? 0)
        }
    }
    
    func mapView(_ mapView: MKMapView,viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        if annotation is PinAnnotation {
            let pinAnnotationView = MKPinAnnotationView(annotation: annotation,reuseIdentifier: "myPin")
            
            pinAnnotationView.isDraggable = true
            pinAnnotationView.canShowCallout = true
            pinAnnotationView.animatesDrop = true

            let deleteButton = UIButton(type: UIButton.ButtonType.custom) as UIButton
            deleteButton.frame.size.width = 44
            deleteButton.frame.size.height = 44

            deleteButton.setImage(UIImage(named: "ic_loc"),for: .normal)

            pinAnnotationView.leftCalloutAccessoryView = deleteButton
    

            return pinAnnotationView
        }

        return nil
    }
    
    
    
}
